import jwt

#创建类
class Myjwt():
    def __init__(self):
        self.SECRET_KEY = "asdasd12!@#WSDAa__+-8/**45131387asdasdCJKZL"

    #生成jwt
    def jwt_encode(self,data):
        token = jwt.encode(data,self.SECRET_KEY,algorithm='HS256')
        #结果字节型 转换
        return str(token,encoding='utf8')
    #解密jwt
    def jwt_decode(self,token):
        # 考虑没有token 加try
        try:
            #先解密
            data = jwt.decode(token,self.SECRET_KEY,algorithms='HS256')
            #在加密
            newtoken = jwt.encode(data,self.SECRET_KEY,algorithm='HS256')
            #在返回新的jwt
            return str(newtoken,encoding='utf8')
        except:
            return None

    #对比jwt
    def check(self,token,newtoken):
        if token == newtoken:
            return True
        return False


myjwt = Myjwt()

#生成jwt
# data= {'data':{'user':'asdasd','id':2}}
# print(myjwt.jwt_encode(data))

#解密生成新的token
# print(myjwt.jwt_decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXIiOiJhc2Rhc2QiLCJpZCI6Mn19.8uz20rGKDTCnjGqE9fuEs0pVIB7NmQZXa08x5Xtnq1Q'))

#对比token
# print(myjwt.check('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXIiOiJhc2Rhc2QiLCJpZCI6Mn19.8uz20rGKDTCnjGqE9fuEs0pVIB7NmQZXa08x5Xtnq1Q','eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXIiOiJhc2Rhc2QiLCJpZCI6Mn19.8uz20rGKDTCnjGqE9fuEs0pVIB7NmQZXa08x5Xtnq1Q'))